package com.ketty;

import java.sql.*;
import java.util.ArrayList;

import com.google.common.collect.Lists;
import com.ketty.entiy.User;

/**
 * 最原生的jdbc操作方法，实现加载驱动，获取容器，生产容器对象，执行语句加载结果集，结果集封装
 * 1.导入JDBC驱动包
 * 2.通过DriverManager注册启动
 * 3.创建连接
 * 4.创建Statement
 * 5.CRUD
 * 6.操作结果集
 * 7.关闭连接
 */
public class JdbcDemo {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        ArrayList<User> userList = Lists.newArrayList();
        try {
            connection = DriverManager.getConnection("", "", "");
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from user");
            while (resultSet.next()) {
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                int age = resultSet.getInt(3);
                userList.add(new User(id, name, age));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
